package com.dede.getmusic.module.home

import android.graphics.Color
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Build
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import com.arlib.floatingsearchview.FloatingSearchView
import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion
import com.dede.getmusic.R
import com.dede.getmusic.R.id.*
import com.dede.getmusic.base.BaseActivity
import com.dede.getmusic.data.SearchInfo
import com.zhy.view.flowlayout.TagFlowLayout
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.toast


class MainActivity : BaseActivity(), FloatingSearchView.OnMenuItemClickListener, IMainView {

    override fun getLayoutId() = R.layout.activity_main

    private val presenter by lazy { MainPresenter(this) }

    private val listAdapter by lazy { SearchListAdapter(R.layout.item_search_layout, emptyList()) }

    private val mediaPlayer by lazy { MediaPlayer() }

    private val searchList by lazy { presenter.getSearchList() }

    private lateinit var flowLayout: TagFlowLayout

    override fun initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window = window
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = Color.TRANSPARENT
        }

        val layoutParams = collapsing_tool_bar.layoutParams
        layoutParams.height = (resources.displayMetrics.widthPixels * 1080 / 1920 + .5).toInt()
        collapsing_tool_bar.layoutParams = layoutParams
        collapsing_tool_bar.setExpandedTitleColor(Color.WHITE)
        collapsing_tool_bar.setCollapsedTitleTextColor(Color.WHITE)

        search_view.setOnLeftMenuClickListener(object : FloatingSearchView.OnLeftMenuClickListener {
            override fun onMenuClosed() {}

            override fun onMenuOpened() {
                search_view.setSearchFocused(true)
            }
        })
        search_view.setOnMenuItemClickListener(this)
        search_view.setOnSearchListener(object : FloatingSearchView.OnSearchListener {
            override fun onSearchAction(currentQuery: String?) {
                if (currentQuery.isNullOrBlank().not()) {
                    refresh_layout.isRefreshing = true
                    presenter.searchMusic(currentQuery!!)
                }
            }

            override fun onSuggestionClicked(searchSuggestion: SearchSuggestion?) {
            }
        })

        listAdapter.setOnItemClickListener { _, _, position ->
            val songsBean = listAdapter.data[position]
            presenter.loadMusicLink(songsBean)
        }
        listAdapter.setOnLoadMoreListener({ presenter.loadMoreMusic() }, recycler_view)

        refresh_layout.setOnRefreshListener {
            refresh_layout.isRefreshing = true
            presenter.searchMusic()
        }

        refresh_layout.setColorSchemeResources(R.color.colorAccent)

        val header = layoutInflater.inflate(R.layout.layout_header_seacrh_his, null)
        flowLayout = header.find(R.id.flow_layout)
        header.find<View>(R.id.tv_clean_search_his).onClick { presenter.clearSearchHis() }
        flowLayout.adapter = SearchHisAdapter(this, searchList)
        flowLayout.setOnTagClickListener { _, position, _ ->
            search_view.setSearchText(searchList[position])
            search_view.setSearchFocused(true)
            true
        }

        listAdapter.addHeaderView(header)
        listAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.iv_download -> {
                    val songsBean = listAdapter.getItem(position)
                    presenter.downloadMusic(songsBean!!)
                }
            }
        }

        recycler_view.adapter = listAdapter
        recycler_view.layoutManager = LinearLayoutManager(this)

        presenter.loadImg(iv_bing)
    }

    override fun loadMusicLinkFinish(link: String) {
        float_bar.visibility = View.GONE
        mediaPlayer.reset()
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
        mediaPlayer.setDataSource(link)
        mediaPlayer.prepareAsync()
        mediaPlayer.setOnPreparedListener {
            it.start()
            float_bar.visibility = View.VISIBLE
            float_bar.setImageResource(R.drawable.ic_pause)
            float_bar.onClick {
                if (!mediaPlayer.isPlaying) {
                    mediaPlayer.start()
                    float_bar.setImageResource(R.drawable.ic_pause)
                } else {
                    mediaPlayer.pause()
                    float_bar.setImageResource(R.drawable.ic_play)
                }
            }
        }
        mediaPlayer.setOnBufferingUpdateListener { _, percent ->
            Log.i(TAG, percent.toString())
        }
        mediaPlayer.setOnErrorListener { _, what, extra ->
            toast("播放出错")
            float_bar.visibility = View.GONE
            false
        }
    }

    override fun initData() {
        presenter.requestPer(this)
    }

    override fun refreshMusicFinish(key: String, data: List<SearchInfo.SongsBean>, hasMore: Boolean) {
        listAdapter.setKey(key)
        listAdapter.setNewData(data)
        if (!hasMore) {
            listAdapter.loadMoreEnd()
        }
        search_view.setSearchFocused(false)
        refresh_layout.isRefreshing = false
    }

    override fun loadMoreMusicFinish(data: List<SearchInfo.SongsBean>, hasMore: Boolean) {
        listAdapter.addData(data)
        if (hasMore) {
            listAdapter.loadMoreComplete()
        } else {
            listAdapter.loadMoreEnd()
        }
    }

    override fun error(msg: String, isLoadMore: Boolean) {
        if (isLoadMore)
            listAdapter.loadMoreFail()
        toast(msg)
        refresh_layout.isRefreshing = false
    }

    override fun refreshSearchHis(list: List<String>) {
        searchList.clear()
        searchList.addAll(list)
        flowLayout.adapter.notifyDataChanged()
    }

    override fun onActionMenuItemSelected(item: MenuItem?) {
        when (item?.itemId) {
            R.id.menu_about -> {
                toast("关于")
            }
            R.id.menu_search -> {
                val query = search_view.query
                if (query.isNotBlank()) {
                    refresh_layout.isRefreshing = true
                    presenter.searchMusic(query)
                }
            }
        }
    }

    override fun onBackPressed() {
        if (search_view.setSearchFocused(false)) {
            return
        }
        super.onBackPressed()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mediaPlayer.isPlaying)
            mediaPlayer.release()
    }
}
